<?php

namespace dk\widget;

class Img extends Base {
    use \dk\traits\Singleton;

    /**
     * @param \weixin\core\View $plug
     */
    function bindHandle($plug) {
        $plug->regPlug('img', function ($params){
            if(!is_array($params)){
                $params = array();
                $args = func_get_args();
                $params['src'] = $args[0];
                if(isset($args[1]))
                    $params['width'] = $args[1];
                if(isset($args[2]))
                    $params['height'] = $args[2];
                if(isset($args[3]))
                    $params['mini'] = $args[3];
            }
            if(!isset($params['nomini'])){
                $params['mini'] = true;
            }

            return $this->render($params);
        });
        $plug->regPlug('imgMini', function ($params){
            if(!is_array($params)){
                $params = array();
                $args = func_get_args();
                $params['src'] = $args[0];
                if(isset($args[1]))
                    $params['width'] = $args[1];
                if(isset($args[2]))
                    $params['height'] = $args[2];
            }
            $params['mini'] = true;
            $params['class'] = 'img-thumbnail';
            return $this->render($params);
        });
    }

    /**
     * @param $files
     * @return string
     */
    function render($params){
        $this->setRequest($params);

        $src = $this->q('src');
        if(!$src){
            return null;
        }
        if(strpos($src, 'upload') === 0){
            $src = 'http://www.jc001.cn/' . $src;
        }

        $attrs = '';
        if(($attr = $this->q('w')) || ($attr = $this->q('width'))){
            $attrs .= ' width="' . $attr . '"';
        }
        if($attr = $this->q('h') || ($attr = $this->q('height'))){
            $attrs .= ' height="' . $attr . '"';
        }

        if($attr = $this->q('class')){
            $attrs .= ' class="' . $attr . '"';
        }
        
        if($this->q('mini') == 1 
            && !is_numeric(strpos($src, "_s")) 
            && !is_numeric(strpos($src, 'images'))
            ){
            $src = preg_replace('/\.(jpg|gif)$/', '_s.$1', $src);
        }

        return "<img src=\"{$src}\"{$attrs}/>";
    }
}